package com.demo.datastructure.stack;

/**
 * @description: 实现一个简单的栈
 * @author: ljr
 * @time: 2021/8/17 10:21
 */
public class SimpleStack<K> implements Stack<K>{

    private Node head;

    private Node tail;

    private int length;

    @Override
    public void push(K value){
        length++;
        Node newNode = new Node(value, head);
        if(head == null){
            tail = newNode;
        }
        head = newNode;
    }

    @Override
    public K pop(){
        if(length == 0) return null;
        Node oldNode = head;
        head = head.next;
        oldNode.next = null;
        return (K) oldNode.value;
    }

    @Override
    public K peek(){
        return (K)head.value;
    }

    @Override
    public int size(){
        return length;
    }

    @Override
    public boolean isEpmty(){
        return head == null;
    }


    private static class Node<K>{
        private K value;

        private Node next;

        public Node(K value, Node next) {
            this.value = value;
            this.next = next;
        }
    }

    public static void main(String[] args){
        SimpleStack<Integer> stack = new SimpleStack();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        while (!stack.isEpmty()){
            System.out.println(stack.pop());
        }
    }
}
